const VueFilenameInjector = require('./tools/vue-filename-injector')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const UglifyPlugin = require('uglifyjs-webpack-plugin')
const CompressionPlugin = require('compression-webpack-plugin')
    // 拼接路径
const resolve = dir => require('path').join(__dirname, dir)
const productionGzipExtensions = ['js', 'css']

// 增加环境变量
process.env.VUE_APP_VERSION = require('./package.json').version
process.env.VUE_APP_BUILD_TIME = require('dayjs')().format('YYYY-M-D HH:mm:ss')

// 基础路径 注意发布之前要先修改这里
let publicPath = '/'
const host = '1.15.92.12:6003'
    // const host = 'localhost:6003'



module.exports = {
    // productionSourceMap : process.env.node_ENV != 'production',
    filenameHashing: false,
    configureWebpack: (config) => {


        // lodash : {
        //   commonjs: "lodash",
        //   commonjs2: "lodash",
        //   amd: "lodash",
        //   root: "_"
        // }


        Object.assign(config, {
                externals: {

                    // 要引入的资源的名字：该模块提供给外部引用的名字(由对应的库自定)
                    'vue': 'Vue',
                    'vuex': 'Vuex',
                    // 'vue-router': 'VueRouter',
                    'element-ui': 'ELEMENT',
                    'echarts': 'echarts',
                    'axios': 'axios',
                    // 'lodash' : 'lodash'
                }
            })
            // .plugin('html')
            // .tap(args => {
            //     args[0].development = process.env.NODE_ENV != 'production';
            //   return args;
            // })

        if (process.env.NODE_ENV == 'production') {

            config.mode = 'production'
                // 将每个依赖包打包成单独的js文件
            let optimization = {
                runtimeChunk: 'single',
                splitChunks: {
                    chunks: 'all',
                    maxInitialRequests: Infinity,
                    minSize: 20000,
                    cacheGroups: {
                        vendor: {
                            test: /[\\/]node_modules[\\/]/,
                            name(module) {
                                // get the name. E.g. node_modules/packageName/not/this/part.js
                                // or node_modules/packageName
                                const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
                                    // npm package names are URL-safe, but some servers don't like @ symbols
                                return `npm.${packageName.replace('@', '')}`
                            }
                        }
                    }
                },

                // minimizer: [new UglifyPlugin({
                //     uglifyOptions: {
                //         warnings: false,
                //         compress: {

                //             drop_console: true, // console
                //             drop_debugger: false,
                //             pure_funcs: ['console.log'] // 移除console
                //         }
                //     }
                // })]
            }
            Object.assign(config, {
                optimization
            })

            config.plugins.push(new CompressionPlugin({
                    filename: '[path].gz[query]',
                    algorithm: 'gzip',
                    test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
                    threshold: 10240,
                    minRatio: 0.8
                }))
                // config.plugins.push(new webpack.ProvidePlugin({'lodash':'lodash'}))


        }


    },



    publicPath, // 根据你的实际情况更改这里
    lintOnSave: true,
    devServer: {
        publicPath, // 和 publicPath 保持一致
        proxy: {
            '/api': {
                target: `http://${host}`,
            }
        }
    },
    css: {
        loaderOptions: {
            // 设置 scss 公用变量文件
            sass: {
                data: `@import '~@/assets/style/public.scss';`
            }
        }

    },
    // 默认设置: https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-service/lib/config/base.js
    chainWebpack: config => {
        /**
         * 删除懒加载模块的 prefetch preload，降低带宽压力
         * https://cli.vuejs.org/zh/guide/html-and-static-assets.html#prefetch
         * https://cli.vuejs.org/zh/guide/html-and-static-assets.html#preload
         * 而且预渲染时生成的 prefetch 标签是 modern 版本的，低版本浏览器是不需要的
         */
        // if (process.env.NODE_ENV != 'production'){
        //         config.plugin('webpack-bundle-analyzer')
        //        .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
        // }


        config.plugins
            .delete('prefetch')
            .delete('preload')
            // 解决 cli3 热更新失效 https://github.com/vuejs/vue-cli/issues/1559
        config.resolve
            .symlinks(true)
        config
        // 开发环境
            .when(process.env.NODE_ENV === 'development',
                // sourcemap不包含列信息
                config => config.devtool('cheap-source-map')
            )
            // TRAVIS 构建 vue-loader 添加 filename
            .when(process.env.VUE_APP_BUILD_MODE === 'TRAVIS' || process.env.NODE_ENV === 'development',
                VueFilenameInjector(config, {
                    propName: process.env.VUE_APP_SOURCE_VIEWER_PROP_NAME
                })
            )
            // svg
        const svgRule = config.module.rule('svg')
        svgRule.uses.clear()
        svgRule
            .include
            .add(resolve('src/assets/svg-icons/icons'))
            .end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({
                symbolId: 'd2-[name]'
            })
            .end()
            // image exclude
        const imagesRule = config.module.rule('images')
        imagesRule
            .test(/\.(png|jpe?g|gif|webp|svg)(\?.*)?$/)
            .exclude
            .add(resolve('src/assets/svg-icons/icons'))
            .end()
            // 重新设置 alias
        config.resolve.alias
            .set('@api', resolve('src/api'))
            // 判断环境加入模拟数据
        const entry = config.entry('app')
        if (process.env.NODE_ENV == 'development') {
            entry
                .add('@/mock')
                .end()
        }

    },
    // i18n
    pluginOptions: {
        i18n: {
            locale: 'zh-chs',
            fallbackLocale: 'en',
            localeDir: 'locales',
            enableInSFC: true
        }
    }
}